package com.scorpio.utils;

import com.scorpio.baen.UserInfo;

import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 客户管理工具
 */
public class ClientManager {
    private final HashMap<SocketChannel, UserInfo> mClinetCache = new HashMap<>();
    private static ClientManager mClientManager;

    public static ClientManager getInstance() {
        if (mClientManager == null) {
            mClientManager = new ClientManager();
        }
        return mClientManager;
    }

    /**
     * 添加新的客户
     *
     * @param client
     * @param info
     */
    public synchronized void addClinet(SocketChannel client, UserInfo info) {
        if (mClinetCache.get(client) != null) return;
        mClinetCache.put(client, info);
    }

    /**
     * 移除客户
     *
     * @param client
     */
    public synchronized void removeClinet(SocketChannel client) {
        UserInfo info = mClinetCache.get(client);
        if (info != null) {
            mClinetCache.remove(client);
        }
    }

    /**
     * 获取指定客户信息
     *
     * @param client
     * @return
     */
    public synchronized UserInfo getClinet(SocketChannel client) {
        return mClinetCache.get(client);
    }

    /**
     * 获取所有客户
     *
     * @return
     */
    public List<UserInfo> getAllClinet() {
        List<UserInfo> userInfos = new ArrayList<>();
        HashMap<SocketChannel, UserInfo> clinetCache;
        synchronized (this) {
            clinetCache = (HashMap<SocketChannel, UserInfo>) mClinetCache.clone();
        }
        for (SocketChannel key : clinetCache.keySet()) {
            UserInfo info = clinetCache.get(key);
            if (info.getUserId() != null) userInfos.add(info);
        }
        return userInfos;
    }

    /**
     * 根据id获取用户
     *
     * @param userId
     * @return
     */
    public synchronized UserInfo inUsernameGetInfo(String userId) {
        for (SocketChannel key : mClinetCache.keySet()) {
            UserInfo info = mClinetCache.get(key);
            if (info.getUserId() != null && info.getUserId().equals(userId)) {
                return info;
            }
        }
        return null;
    }

    /**
     * 获取指定用户是否在线
     *
     * @param userId
     * @return 反空则表示不在线
     */
    public UserInfo getOnLineUser(String userId) {
        if (userId == null) return null;
        UserInfo info = inUsernameGetInfo(userId);
        if (info != null && info.getStart() == UserInfo.START_RE) {
            return info;
        }
        return null;
    }
}
